import React, { useEffect, useState } from 'react';
import ReactPlayer from 'react-player';
import {Button, Drawer, FloatButton, Input, List, message, Popconfirm} from 'antd';
import axios from 'axios';
import {
    ArrowDownOutlined,
    ArrowUpOutlined,
    DeleteOutlined,
    LikeFilled,
    LikeOutlined,
    MessageOutlined, PlusOutlined
} from "@ant-design/icons";


const { TextArea } = Input;
const Video = () => {

    const [videos, setVideos] = useState(null);
    const [currentIndex, setCurrentIndex] = useState(0);
    const [playable, setPlayable] = useState(true);

    const [open, setOpen] = useState(false);
    const [comments, setComments] = useState([]);
    const [commentCount, setCommentCount] = useState(0);
    const [newComment, setNewComment] = useState("");
    const [commentLoading, setCommentLoading] = useState(false);

    const [likeStatus, setLikeStatus] = useState(false);
    const [likeNumber, setLikeNumber] = useState(0);

    const token = window.sessionStorage.getItem("token");
    console.log("界面token:", token);
    const userId = window.sessionStorage.getItem("userId");
    console.log("userId:", userId);

    // 获取视频列表数据
    useEffect(() => {
        if (!userId) {
            getTemporaryUserId();
        } else {
            getStart(userId);
        }
    }, []);

    const getTemporaryUserId = async () => {
        try {
            const response = await axios.get('http://58.87.105.2:8080/get-temporary-user-id');
            const temporaryUserId = response.data.data;
            window.sessionStorage.setItem("userId", temporaryUserId);
            console.log("temporary-userId:", temporaryUserId);
            getStart(temporaryUserId);
        } catch (error) {
            console.error('Error fetching temporary user ID:', error);
        }
    };

    const getStart = async (userId) => {
        try {
            const response = await axios.get(`http://58.87.105.2:8080/video/get-recommend-videos?userId=${userId}&count=10`);
            const videoList = response.data.data.map(video => ({
                ...video,
                likeNumber: video.likeNumber ?? 0 // 设置默认值为0
            }));
            setVideos(videoList);
            if (videoList.length > 0) {
                const currentVideo = videoList[0];
                setLikeNumber(currentVideo.likeNumber);
                fetchVideoLikeStatus(currentVideo.id);
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    // 获取视频点赞数量
    const fetchVideoLikeStatus = async (videoId) => {
        if (!token) {
            // message.error('尚未登陆');
            return;
        }
        try {
            const response = await axios.get(`http://58.87.105.2:8080/video/${videoId}`,{
                headers: {
                    token: `${token}`,
                }
            });
            if (response.data.code === 0) {
                setLikeStatus(response.data.data.isLiked);
            } else {
                message.error("获取视频点赞状态失败");
            }
        } catch (error) {
            console.error("获取视频点赞状态失败", error);
            message.error("获取视频点赞状态失败");
        }
    };

    // 获取评论数据
    useEffect(() => {
        if (videos && videos.length > 0) {
            fetchCommentCount(videos[currentIndex].id);
            fetchVideoLikeStatus(videos[currentIndex].id);
        }
    }, [currentIndex, videos]);

    const fetchCommentCount = async (videoId) => {
        try {
            const response = await axios.get(`http://58.87.105.2:8080/comment/list?page=1&pageSize=10&videoId=${videoId}`);
            if (response.data.code === 0) {
                setCommentCount(response.data.data.total);
            } else {
                setCommentCount(0);
                message.error("获取评论数量失败");
            }
        } catch (error) {
            console.error("获取评论数量失败", error);
            message.error("获取评论数量失败");
        }
    };
    const fetchComments = () => {
        if (!token) {
            setCommentLoading(true);
            axios.get(`http://58.87.105.2:8080/comment/list?page=1&pageSize=10&videoId=${videos[currentIndex].id}`)
                .then(response => {
                    if (response.data.code === 0) {
                        // console.log(response.data.data.rows);
                        setComments(response.data.data.rows);
                        setCommentCount(response.data.data.rows.length);
                    } else {
                        message.error("获取评论数据失败");
                    }
                })
                .catch(error => {
                    console.error("获取评论数据失败", error);
                    message.error("获取评论数据失败");
                })
                .finally(() => {
                    setCommentLoading(false);
                });
        } else {
            setCommentLoading(true);
            axios.get(`http://58.87.105.2:8080/comment/list?page=1&pageSize=10&videoId=${videos[currentIndex].id}`,
                {
                    headers: {
                        token : `${token}`,
                    },
                })
                .then(response => {
                    if (response.data.code === 0) {
                        // console.log(response.data.data.rows);
                        setComments(response.data.data.rows);
                        setCommentCount(response.data.data.rows.length);
                    } else {
                        message.error("获取评论数据失败");
                    }
                })
                .catch(error => {
                    console.error("获取评论数据失败", error);
                    message.error("获取评论数据失败");
                })
                .finally(() => {
                    setCommentLoading(false);
                });
        }

    };

    // 上一条视频
    const handleUp = () => {
        if (currentIndex === 0) {
            message.info('已经是第一个视频');
        } else {
            setCurrentIndex((prevIndex) => (prevIndex - 1));
            setPlayable(true);
            setLikeNumber(videos[currentIndex - 1].likeNumber);
            fetchVideoLikeStatus(videos[currentIndex - 1].id);
        }
    };

    // 下一条视频
    const handleDown = () => {
        if (currentIndex === videos.length - 1) {
            message.info('已经是最后一个视频');
        } else {
            setCurrentIndex((prevIndex) => (prevIndex + 1));
            setPlayable(true);
            setLikeNumber(videos[currentIndex + 1].likeNumber);
            fetchVideoLikeStatus(videos[currentIndex + 1].id);
        }
    };

    if (videos === null || videos.length === 0) {
        return (
            <div>暂无推荐视频</div>
        );
    }

    // 点赞视频
    const handleLike = () => {
        if (!token) {
            message.error('尚未登陆');
            return;
        }
        const video = videos[currentIndex];
        const likeAction = likeStatus ? 'dislike' : 'like';
        axios.put(`http://58.87.105.2:8080/video/${likeAction}?id=${video.id}`, {}, {
            headers: {
                token: `${token}`
            }
        })
            .then(response => {
                if (response.data.code === 0) {
                    setLikeStatus(!likeStatus);
                    setLikeNumber(likeNumber + (likeStatus ? -1 : 1));
                    // 更新 videos 数组中的 likeStatus 和 likeNumber
                    setVideos(prevVideos =>
                        prevVideos.map((v, index) =>
                            index === currentIndex ? { ...v, liked: !likeStatus, likeNumber: likeNumber + (likeStatus ? -1 : 1) } : v
                        )
                    );
                    message.success(likeStatus ? '取消点赞成功' : '点赞成功');
                } else {
                    message.error(response.data.message || '操作失败');
                }
            })
            .catch(error => {
                console.error('点赞操作失败', error);
                message.error('操作失败');
            });
    };

    const handleComment = () => {
        setOpen(true);
        fetchComments();
    };

    const handleCommentLike = (commentId, isLiked) => {
        if (!token) {
            message.error('尚未登陆');
            return;
        }

        // 找到需要点赞或取消点赞的评论
        const comment = comments.find(comment => comment.id === commentId);
        if (!comment) {
            message.error('未找到该评论');
            return;
        }
        console.log(comment);
        console.log("是否点赞", isLiked);

        // const isLiked = comment.isLiked;
        // 根据评论的当前 isLiked 属性决定进行点赞还是取消点赞操作
        const likeAction = isLiked === 1 ? 'dislike' : 'like';
        const newIsLiked = isLiked === 1 ? 0 : 1;
        console.log("更新点赞", newIsLiked);

        axios.put(`http://58.87.105.2:8080/comment/${likeAction}?id=${commentId}`,{},
            {
            headers: {
                token: `${token}`
            }
        })
            .then(response => {
                if (response.data.code === 0) {
                    // 更新评论列表中的点赞数量和 isLiked 属性
                    setComments(comments.map(comment =>
                        comment.id === commentId ? { ...comment, likeNumber: comment.likeNumber + (isLiked === 1 ? -1 : 1), isLiked: newIsLiked } : comment
                    ));
                    message.success(isLiked === 1 ? '取消点赞成功' : '点赞成功');
                } else {
                    message.error(response.data.message || '操作失败');
                }
            })
            .catch(error => {
                console.error('评论点赞操作失败', error);
                message.error('操作失败');
            });
    };

    const handleCommentDelete = (commentId) => {
        if (!token) {
            message.error('尚未登陆');
            return;
        }
        const comment = comments.find(comment => comment.id === commentId);
        if (!comment) {
            message.error('未找到该评论');
            return;
        }

        // 检查评论的 userId 是否与当前用户的 userId 一致
        if (comment.userId == userId) {
            axios.delete(`http://58.87.105.2:8080/comment/${commentId}`, {
                headers: {
                    token: `${token}`
                }
            })
                .then(response => {
                    if (response.data.code === 0) {
                        setComments(comments.filter(comment => comment.id !== commentId));
                        setCommentCount(commentCount - 1);
                        message.success('删除评论成功');
                    } else {
                        message.error(response.data.message || '操作失败');
                    }
                })
                .catch(error => {
                    console.error('删除评论操作失败', error);
                    message.error('操作失败');
                });
        } else {
            message.error('无法删除他人评论！');
            // return;
        }
    };

    const handleAddComment = () => {
        if (!token) {
            message.error('尚未登陆');
            return;
        }
        if (!newComment) {
            message.error("评论内容不能为空");
            return;
        }

        const formData = new FormData();
        formData.append("content", newComment);
        formData.append("videoId", videos[currentIndex].id);

        axios.post(`http://58.87.105.2:8080/comment`, formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                token: `${token}`
            }
        })
            .then(response => {
                if (response.data.code === 0) {
                    message.success("添加评论成功");
                    setNewComment(""); // 清空输入框
                    fetchComments(); // 重新获取评论列表
                } else {
                    message.error(response.data.message || "添加评论失败");
                }
            })
            .catch(error => {
                console.error("添加评论失败", error);
                message.error("添加评论失败");
            });
    };

    return (
        <>
            <div className="video-container">
                <div>当前视频ID: {videos[currentIndex].id}</div>
                <div>当前视频标题: {videos[currentIndex].title}</div>
                {playable ? (
                    <ReactPlayer
                        url={videos[currentIndex].url}
                        playing={true}
                        loop={true}
                        volume={0.5}
                        onError={() => setPlayable(false)}
                        onReady={() => setPlayable(true)}
                    />
                ) : (
                    <div>无法播放</div>
                )}
            </div>
            <FloatButton.Group
                shape="circle"
                style={{
                    marginRight: '40px',
                }}
            >
                <FloatButton icon={<ArrowUpOutlined />} onClick={handleUp} />
                <FloatButton icon={<ArrowDownOutlined />} onClick={handleDown} />
                <FloatButton icon={likeStatus ? <LikeFilled /> : <LikeOutlined />} description={`${likeNumber}`} onClick={handleLike} />
                <FloatButton icon={<MessageOutlined />} description={`${commentCount}`} onClick={handleComment} />
            </FloatButton.Group>

            <Drawer
                closable
                destroyOnClose
                title={(
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <p>评论（{commentCount}）</p>
                        <Button type="primary" icon={<PlusOutlined />} onClick={handleAddComment}>
                            添加评论
                        </Button>
                    </div>
                )}
                placement="right"
                open={open}
                onClose={() => setOpen(false)}
            >
                <TextArea
                    autoSize
                    value={newComment}
                    onChange={e => setNewComment(e.target.value)}
                    placeholder="输入评论内容"
                />
                <List
                    dataSource={comments}
                    renderItem={comment => (
                        <List.Item key={comment.id}
                                   actions={[
                                       <Button
                                           type="text" style={{ width: '60px' }}
                                           icon={comment.isLiked === 1 ? <LikeFilled /> : <LikeOutlined />}
                                           onClick={() => handleCommentLike(comment.id, comment.isLiked)}
                                       >
                                           {comment.likeNumber}
                                       </Button>,
                                       <Popconfirm
                                           title="确认删除评论?"
                                           onConfirm={() => handleCommentDelete(comment.id)}
                                           okText="确定"
                                           cancelText="取消"
                                       >
                                           <Button type="text" style={{ width: '60px' }} icon={<DeleteOutlined />} />
                                       </Popconfirm>
                                   ]}
                        >
                            <List.Item.Meta
                                title={`用户ID: ${comment.userId}`}
                                description={comment.content}
                            />
                        </List.Item>
                    )}
                />
            </Drawer>
        </>
    );
};

export default Video;
